import React, { useState, useCallback, useEffect } from 'react';
import { NavBar, Toast } from 'antd-mobile';
import { 
  ClockCircleOutline
} from 'antd-mobile-icons';
import { useNavigate, useLocation } from 'react-router-dom';
import { RefundStatus, RefundReason } from './types/refund';
import type { 
  RefundInfo, 
  ProgressStep,
  OrderInfo
} from './types/refund';
import axios from '../../axios';
import './Com/Refund.css';

// 格式化时间为北京时间
const formatBeijingTime = (timeString?: string): string => {
  if (!timeString) return '';
  const date = new Date(timeString);
  if (isNaN(date.getTime())) return '';
  // 确保使用北京时间（UTC+8）
  const beijingTime = new Date(date.getTime() + (8 * 60 * 60 * 1000));
  const year = beijingTime.getUTCFullYear();
  const month = String(beijingTime.getUTCMonth() + 1).padStart(2, '0');
  const day = String(beijingTime.getUTCDate()).padStart(2, '0');
  const hours = String(beijingTime.getUTCHours()).padStart(2, '0');
  const minutes = String(beijingTime.getUTCMinutes()).padStart(2, '0');
  const seconds = String(beijingTime.getUTCSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

const RefundPending: React.FC = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const [refundInfo, setRefundInfo] = useState<RefundInfo | null>(null);
  const [loading, setLoading] = useState<boolean>(true);

  // 获取退款信息
  const fetchRefundInfo = useCallback(async (): Promise<void> => {
    try {
      setLoading(true);
      
      // 从路由参数中获取传递的数据
      const orderData = location.state?.order as OrderInfo;
      
      if (!orderData) {
        Toast.show('未找到订单信息');
        navigate(-1);
        return;
      }

      // 调用后端接口获取退款详情
      const orderId = orderData.id || orderData.orderId;
      const response = await axios.get(`http://localhost:3000/hy/after-sales/${orderId}`);
      
      if (response.data.code === 200) {
        const data = response.data.data;
        
        // 构建退款信息
        const refundInfo: RefundInfo = {
          refundId: `TK${Date.now()}`,
          orderId: data.orderId || '',
          productName: `${data.products?.length || 0}件商品`,
          refundAmount: data.refundAmount || 0,
          applyTime: data.refundTime || formatBeijingTime(new Date().toISOString()),
          refundReason: data.refundReason || RefundReason.OTHER,
          status: RefundStatus.PENDING
        };
        
        setRefundInfo(refundInfo);
      } else {
        Toast.show(response.data.message || '获取退款信息失败');
      }
    } catch (error) {
      Toast.show('获取退款信息失败');
      console.error('Fetch error:', error);
    } finally {
      setLoading(false);
    }
  }, [location.state, navigate]);

  // 构建进度步骤
  const buildProgressSteps = (refundInfo: RefundInfo): ProgressStep[] => {
    return [
      {
        title: '提交申请',
        desc: '您已成功提交退款申请',
        time: refundInfo.applyTime || '',
        active: true
      },
      {
        title: '审核中',
        desc: '客服正在审核您的退款申请',
        time: refundInfo.applyTime || '', // 申请后立即开始审核
        active: true
      },
      {
        title: '退款处理',
        desc: '审核通过后将开始退款处理',
        time: '', // 待处理
        active: false
      },
      {
        title: '退款完成',
        desc: '退款金额将原路返回',
        time: '', // 待完成
        active: false
      }
    ];
  };

  // 页面加载时获取退款信息
  useEffect(() => {
    fetchRefundInfo();
  }, [fetchRefundInfo]);

  if (loading) {
    return (
      <div className="refund-page">
        <NavBar 
          className="refund-navbar"
          onBack={() => navigate(-1)}
        >
          退款进度
        </NavBar>
        <div style={{ 
          display: 'flex', 
          justifyContent: 'center', 
          alignItems: 'center', 
          height: '50vh' 
        }}>
          加载中...
        </div>
      </div>
    );
  }

  if (!refundInfo) {
    return (
      <div className="refund-page">
        <NavBar 
          className="refund-navbar"
          onBack={() => navigate(-1)}
        >
          退款进度
        </NavBar>
        <div style={{ 
          display: 'flex', 
          justifyContent: 'center', 
          alignItems: 'center', 
          height: '50vh' 
        }}>
          未找到退款信息
        </div>
      </div>
    );
  }

  return (
    <div className="refund-page">
      <NavBar 
        className="refund-navbar"
        onBack={() => navigate(-1)}
      >
        退款进度
      </NavBar>

      <div className="refund-container">
        {/* 状态提示 */}
        <div className="refund-card">
          <div className="refund-header">
            <ClockCircleOutline className="refund-status-icon" style={{ color: '#fa8c16' }} />
            <div className="refund-status-title" style={{ color: '#fa8c16' }}>
              正在审核中
            </div>
          </div>
          <div style={{ 
            fontSize: '0.36rem', 
            color: '#666',
            marginBottom: '0.3rem'
          }}>
            我们正在仔细审核您的退款申请，请耐心等待
          </div>
          <div style={{ 
            fontSize: '0.32rem', 
            color: '#999'
          }}>
            预计处理时间：{refundInfo.estimatedTime}
          </div>
        </div>



        {/* 进度追踪 */}
        <div className="refund-progress-container">
          <div className="refund-progress-header">
            <ClockCircleOutline className="refund-progress-icon" style={{ color: '#fa8c16' }} />
            <div className="refund-progress-title">退款进度</div>
          </div>
          <div className="refund-progress-steps">
            {buildProgressSteps(refundInfo).map((step: ProgressStep, index: number) => (
              <div key={index} className={`refund-progress-step ${step.active ? 'active' : ''}`}>
                <div className="refund-progress-dot" />
                <div className="refund-progress-content">
                  <div className="refund-progress-step-title">{step.title}</div>
                  <div className="refund-progress-step-desc">{step.desc}</div>
                  {step.time && (
                    <div className="refund-progress-step-time">{formatBeijingTime(step.time)}</div>
                  )}
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* 温馨提示 */}
        <div className="refund-tip-section">
          <div className="refund-tip-title">温馨提示</div>
          <div className="refund-tip-content">
            • 我们会在1-3个工作日内完成审核<br/>
            • 审核通过后，退款将在5-7个工作日内原路返回
          </div>
        </div>
      </div>


    </div>
  );
};

export default RefundPending; 